package com.cheyunkeji.er.fragment.evaluate;

import android.graphics.Bitmap;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.EvaluateWorkflowActivity;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.utils.BitmapUtils;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.evaluate.ColourImageBaseLayerView;
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

/** Created by Michael on 2017/4/7 15:27. */
public class CarLacquerCheckFragment extends BaseFragment
    implements RadioGroup.OnCheckedChangeListener,
        EvaluateWorkflowActivity.OnOutActionListener,
        ColourImageBaseLayerView.OnColorAreaTouchedListener {

  public static final int PAGE_INDEX = 6;
  private static final String TAG = CarLacquerCheckFragment.class.getSimpleName();
  private final int YUAN_CHANG_QI = 1, PEN_QI = 2, BAN_JIN = 3;

  @BindView(R.id.iv_layer_container)
  ColourImageBaseLayerView ivLayerContainer;

  @BindView(R.id.rb_yc)
  RadioButton rbYc;

  @BindView(R.id.rb_pq)
  RadioButton rbPq;

  @BindView(R.id.rb_bj)
  RadioButton rbBj;

  @BindView(R.id.rg_color_select)
  RadioGroup rgColorSelect;

  @BindView(R.id.tv_previous_step)
  TextView tvPreviousStep;

  @BindView(R.id.tv_next_step)
  TextView tvNextStep;

  private int CURRENT_CHECKED_STATE = YUAN_CHANG_QI;

  private int[] ycqDrawablesId = Constants.ycqDrawablesId;

  private int[] pqDrawablesId = Constants.pqDrawablesId;

  private int[] bjDrawablesId = Constants.bjDrawablesId;

  private Bitmap[] bitmapss;

  private List<EvaluateDetailResult2.DetectionBean.PaintBean> paintList = null;
  private Runnable mTask;

  @Override
  protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
    contentView = inflater.inflate(R.layout.er_car_lacquer_check1, container, false);
    ButterKnife.bind(this, contentView);
  }

  @Override
  protected void init() {

    paintList = new ArrayList<>();
    initBitmapLayer();
    ivLayerContainer.setListener(this);
  }

  /** 初始化图层 */
  private void initBitmapLayer() {

    if (null == bitmapss || bitmapss.length == 0) {
      bitmapss = new Bitmap[ycqDrawablesId.length];
      for (int i = 0; i < ycqDrawablesId.length; i++) {
        bitmapss[i] = BitmapUtils.decodeSampledBitmapFromResource(getActivity(), ycqDrawablesId[i]);
      }
    }

    //        显示已保存的状态对应图片，原厂漆是默认显示的颜色，初始化时不处理
    if (null != MyApplication.getInstance().getEvaluateResult()
        && null != MyApplication.getInstance().getEvaluateResult().getDetection()
        && null != MyApplication.getInstance().getEvaluateResult().getDetection().getPaint()) {

      paintList.addAll(MyApplication.getInstance().getEvaluateResult().getDetection().getPaint());

      for (EvaluateDetailResult2.DetectionBean.PaintBean paintBean : paintList) {

        if (paintBean.getStatus() == PEN_QI) {
          bitmapss[paintBean.getId()] =
              BitmapUtils.decodeSampledBitmapFromResource(
                  getActivity(), pqDrawablesId[paintBean.getId()]);
        } else if (paintBean.getStatus() == BAN_JIN) {
          bitmapss[paintBean.getId()] =
              BitmapUtils.decodeSampledBitmapFromResource(
                  getActivity(), bjDrawablesId[paintBean.getId()]);
        }
      }
    }

    ivLayerContainer.setBitmaps(bitmapss);
  }

  @Override
  protected void initView() {
    rgColorSelect.setOnCheckedChangeListener(this);
    tvPreviousStep.setOnClickListener(this);
    tvNextStep.setOnClickListener(this);
  }

  @Override
  protected void initData() {}

  @Override
  public void onCheckedChanged(RadioGroup group, int checkedId) {

    switch (checkedId) {
      case R.id.rb_yc:
        CURRENT_CHECKED_STATE = YUAN_CHANG_QI;
        break;
      case R.id.rb_pq:
        CURRENT_CHECKED_STATE = PEN_QI;
        break;
      case R.id.rb_bj:
        CURRENT_CHECKED_STATE = BAN_JIN;
        break;
      default:
        break;
    }
  }

  @Override
  public void onResume() {
    super.onResume();
  }

  @Override
  public void onDestroyView() {
    super.onDestroyView();
  }

  @Override
  public void onClick(View v) {
    super.onClick(v);

    switch (v.getId()) {
      case R.id.tv_previous_step:
        onSaveEvaluateResult(
            new Runnable() {
              @Override
              public void run() {
                goToPreviousPage();
              }
            });

        break;
      case R.id.tv_next_step:
        onSaveEvaluateResult(
            new Runnable() {
              @Override
              public void run() {
                goToNextPage();
              }
            });
      default:
        break;
    }
  }

  @Override
  public void onSaveEvaluateResult(Runnable task) {

    if (null != task) this.mTask = task;

    Log.e(TAG, "onSaveEvaluateResult : " + new Gson().toJson(paintList));

    String myData =
        new StringBuilder("{\"paint\":")
            .append(new Gson().toJson(paintList))
            .append("}")
            .toString();

    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("aid", MyApplication.getInstance().getEvaluateResult().getAid());
    params.put("detection", myData);

    if (MyApplication.getInstance().getEvaluateResult() == null
        || MyApplication.getInstance().getEvaluateResult().getIroute() == null
        || MyApplication.getInstance().getEvaluateResult().getIroute().size() == 0) {
      int[] iroute = new int[15];
      iroute[PAGE_INDEX] = 1;
      String json = new Gson().toJson(iroute);
      Log.e(TAG, "saveData: 评估记录为空或数组为空时 保存记录数组 ：  " + json.substring(1, json.length() - 1));
      params.put("iroute", json.substring(1, json.length() - 1));
    } else {
      MyApplication.getInstance().getEvaluateResult().getIroute().set(PAGE_INDEX, 1);
      String json = new Gson().toJson(MyApplication.getInstance().getEvaluateResult().getIroute());
      params.put("iroute", json.substring(1, json.length() - 1));
      Log.e(
          TAG, "saveData:  保存记录数组 ：记录非空并且数组非空时 保存记录数组 ：   " + json.substring(1, json.length() - 1));
    }

    //        根据评估类型进行保存或编辑
    int evaluateType = ((EvaluateWorkflowActivity) getActivity()).getEvaluateArchiveType();

    //       保存新创建、未上传待评估数据
    if (evaluateType == Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE
        || evaluateType == Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE
        || evaluateType == Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN) {

      ApiClient.postForm(
          ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(),
          params,
          new RespCallback<EvaluateDetailResult2>() {

            @Override
            protected void onRequestFailed(String msg) {
              SToast.show(msg);
              if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                mTask.run();
                mTask = null;
              }
            }

            @Override
            protected void onSuccess(EvaluateDetailResult2 data) {

              if (null != data) {

                MyApplication.getInstance().setEvaluateResult(data);
                if (null != mTask) {
                  mTask.run();
                  mTask = null;
                }
              }
            }

            @Override
            public void onBefore(Request request, int id) {
              showDialog();
            }

            @Override
            public void onAfter(int id) {
              dismissDialog();
            }
          });

    } else if (evaluateType == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {

      ApiClient.postForm(
          ((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(),
          params,
          new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

              // 网络异常
              if (e instanceof UnknownHostException || e instanceof SocketException) {
                SToast.show(R.string.tip_network_error, Gravity.CENTER);
                return;
              }
            }

            @Override
            public void onResponse(String response, int id) {

              try {

                JSONObject obj = new JSONObject(response);
                if (obj.optInt("code") == 1) {
                  //                            SToast.show("保存成功", Gravity.CENTER);

                  Log.e(TAG, "onResponse: 编辑成功 : " + obj.optString("data"));

                  if (null != mTask) {
                    mTask.run();
                    mTask = null;
                  }

                } else {
                  SToast.show(obj.optString("msg"));
                  if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                    mTask.run();
                    mTask = null;
                  }
                }

              } catch (JSONException e) {
                e.printStackTrace();
              }
            }

            @Override
            public void onBefore(Request request, int id) {
              showDialog();
            }

            @Override
            public void onAfter(int id) {
              dismissDialog();
            }
          });
    }
  }

  private void goToPreviousPage() {
    ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(AppearanceCheckFragment.PAGE_INDEX);
  }

  private void goToNextPage() {
    ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(TyreCheckFragment.PAGE_INDEX);
  }

  @Override
  public void onAreaTouched(int areaIndex) {

    switch (CURRENT_CHECKED_STATE) {
      case YUAN_CHANG_QI:
        bitmapss[areaIndex] =
            BitmapUtils.decodeSampledBitmapFromResource(getActivity(), ycqDrawablesId[areaIndex]);
        break;
      case PEN_QI:
        bitmapss[areaIndex] =
            BitmapUtils.decodeSampledBitmapFromResource(getActivity(), pqDrawablesId[areaIndex]);
        break;
      case BAN_JIN:
        bitmapss[areaIndex] =
            BitmapUtils.decodeSampledBitmapFromResource(getActivity(), bjDrawablesId[areaIndex]);
        break;

      default:
        break;
    }

    ivLayerContainer.setBitmaps(bitmapss);
    Log.e(TAG, "onAreaTouched: Touched Area Index :  " + areaIndex);

    //       如果有漆面状态保存记录，则直接修改
    for (EvaluateDetailResult2.DetectionBean.PaintBean paintBean : paintList) {

      if (paintBean.getId() == areaIndex) {
        paintBean.setStatus(CURRENT_CHECKED_STATE);
        return;
      }
    }

    //        无添加记录，则新建一条
    paintList.add(
        new EvaluateDetailResult2.DetectionBean.PaintBean(areaIndex, CURRENT_CHECKED_STATE));
  }
}
